using System.Collections.ObjectModel;

using Bee.Base.Abstractions;
using Bee.Base.Abstractions.Tasks;
using Bee.Base.Models.Tasks;
using Bee.Base.ViewModels;

using FFMpegCore;

using Ke.Bee.Localization.Localizer.Abstractions;

using LanguageExt;

namespace Bee.Plugin.Multimedia.Tasks;

public class VideoMergeTaskHandler(ICoverHandler coverHandler, ILocalizer localizer, ToastrViewModel toastr) :
    TaskHandlerBase<VideoMergeArguments>(coverHandler)
{
    private readonly ILocalizer _l = localizer;
    private readonly ToastrViewModel _toastr = toastr;

    public override Task ExecuteAsync(ObservableCollection<TaskItem> taskItems,
        VideoMergeArguments arguments,
        CancellationToken cancellationToken = default,
        Action<Fin<Unit>>? onItemExecuted = null)
    {
        cancellationToken.ThrowIfCancellationRequested();

        // 判断输入文件类型是否一致
        if (taskItems.Select(x => Path.GetExtension(x.Input).ToLower()).Distinct().Count() > 1)
        {
            _toastr.ToastrError(_l["Bee.Plugin.Multimedia.Invalid.InputFormatInconsistency"]);
            return Task.CompletedTask;
        }

        // 分析原视频信息
        //var analysis = FFProbe.Analyse(taskItem.Input);

        var fileName = Path.GetFileNameWithoutExtension(taskItems[0].Input);
        var ext = Path.GetExtension(taskItems[0].Input);

        //Console.WriteLine(ext);

        // 输出文件
        var outputFile = Path.Combine(arguments.OutputDirectory,
            $"{fileName}.{arguments.OutputFormat}")
            ;

        FFMpeg.Join(outputFile, taskItems.Select(x => x.Input).ToArray());

        foreach (var item in taskItems)
        {
            item.Percent = 100;
        }

        return Task.CompletedTask;
    }
}